const all = [
  {id: 1, name: 'n1', parent_id: 0},
  {id: 2, name: 'n2', parent_id: 0},
  {id: 3, name: 'n3', parent_id: 0},
  {id: 4, name: 'n4', parent_id: 1},
  {id: 5, name: 'n5', parent_id: 1},
  {id: 6, name: 'n6', parent_id: 2},
  {id: 7, name: 'n7', parent_id: 3},
  {id: 8, name: 'n8', parent_id: 4},
  {id: 9, name: 'n9', parent_id: 8}
]
/**
 * 将直接从数据库查出的每个节点只存父节点ID的数据，转为更直观的json树形数据。
 * 1.all中必须包含根节点，形似[{},{},{}]
 * 2.all中每个元素至少有id和parent_id两个字段
 * @param all 需要转化的节点原始数据
 * @return 树形结构json
 */
exports.convertTree = all => {
  const tmp = {};
  for (let i = 0; i < all.length; i++) {
    const item = all[i];
    if (!tmp[item.id]) {
      tmp[item.id] = {};
    }
    // 根据引用类型数据特性，所有tmp的节点，key键为tmp[item.id]的数据都是指向同一堆地址，修改一个{tmp[item.id]:xxx}，其他的也会一起变。
    for (const key in item) {
      if (item.hasOwnProperty(key)) tmp[item.id][key] = item[key];
    }
    if (!('children' in tmp[item.id])) tmp[item.id].children = [];
    if (tmp[item.father_id]) {
      tmp[item.father_id].children.push(tmp[item.id]);
    } else {
      tmp[item.father_id] = {children: [tmp[item.id]]};
    }
  }
  return tmp[0].children;
};
